package com.sgcc.ln.pmos.common.http;

import android.content.Context;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }


    public DownloadUtil() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.hostnameVerifier(getHostnameVerifier());
        builder.sslSocketFactory(getSSLSocketFactory());
        okHttpClient = builder.build();
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

    /**
     * description 忽略https证书验证
     * `在这里插入代码片`
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    public SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * description 忽略https证书验证
     *
     * @author yanzy
     * @version 1.0
     * @date 2021/9/8 14:42
     */
    private TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }


    public void downloadPdf(Context context, String url, OnDownloadListener onDownloadListener) {
        download(context, HttpInterConst.BASEURL_PDF + url,
                context.getExternalFilesDir("pdf"),
                System.currentTimeMillis() + ".pdf",
                onDownloadListener);

    }

    public void downloadPdf1(Context context, String url, OnDownloadListener onDownloadListener) {
        download(context, url,
                context.getExternalFilesDir("pdf"),
                System.currentTimeMillis() + ".pdf",
                onDownloadListener);

    }

    public void downloadPdf2(Context context, String url, OnDownloadListener onDownloadListener) {
        download(context, url,
                context.getExternalFilesDir("pdf"),
                onDownloadListener);

    }

    public void downloadApk(Context context, String url, String name, OnDownloadListener onDownloadListener) {
        download(context, url,
                context.getExternalFilesDir("apk"),
                "ejy_" + name + ".apk",
                onDownloadListener);

    }

    public void download(Context context, final String url, File pathFile,
                         final OnDownloadListener listener) {
        Map<String, Object> params = new HashMap<>();
        params.put("code", "");
        HttpRequestUtils.getInstance().request(params, url, new com.zhy.http.okhttp.callback.Callback() {
            @Override
            public Object parseNetworkResponse(Response response, int id) throws Exception {
                String fileName = "";
                Headers headers = response.headers();
                String content_disposition = headers.get("content-disposition");
                if (content_disposition.contains("fileName")) {
                    String str[] = content_disposition.split(";");
                    if (str.length >= 2) {
                        fileName = java.net.URLDecoder.decode(str[1], "UTF-8");
                        int index = fileName.indexOf("=");
                        if (index != -1) {
                            fileName = fileName.substring(index + 1);
                        }
                    }
                }


                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                File file = new File(pathFile, fileName);
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onDownloading(progress);
                            }
                        });
                    }
                    fos.flush();
                    //下载完成

                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDownloadSuccess(file);
                        }
                    });

                } catch (Exception e) {
                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDownloadFailed(e);
                        }
                    });

                } finally {

                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }
                }
                return null;
            }

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(Object response, int id) {

            }
        });

    }

    /**
     * @param url          下载连接
     * @param pathFile     下载地址
     * @param destFileName 下载文件名称，后面记得拼接后缀，否则手机没法识别文件类型
     * @param listener     下载监听
     */
    public void download(Context context, final String url, File pathFile,
                         final String destFileName, final OnDownloadListener listener) {
        new Thread(new Runnable() {
            public void run() {
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                //异步请求
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        // 下载失败监听回调
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onDownloadFailed(e);
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        InputStream is = null;
                        byte[] buf = new byte[2048];
                        int len = 0;
                        FileOutputStream fos = null;

                        File file = new File(pathFile, destFileName);
                        try {

                            is = response.body().byteStream();
                            long total = response.body().contentLength();
                            fos = new FileOutputStream(file);
                            long sum = 0;
                            while ((len = is.read(buf)) != -1) {
                                fos.write(buf, 0, len);
                                sum += len;
                                int progress = (int) (sum * 1.0f / total * 100);
                                //下载中更新进度条
                                ThreadUtils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        listener.onDownloading(progress);
                                    }
                                });
                            }
                            fos.flush();
                            //下载完成

                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listener.onDownloadSuccess(file);
                                }
                            });

                        } catch (Exception e) {
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    listener.onDownloadFailed(e);
                                }
                            });

                        } finally {

                            try {
                                if (is != null) {
                                    is.close();
                                }
                                if (fos != null) {
                                    fos.close();
                                }
                            } catch (IOException e) {

                            }
                        }
                    }
                });
            }
        }).start();
    }

    public void downloadGET(Context context, final String url, File pathFile,
                            final DownloadUtil.OnDownloadListener listener) {
        Map<String, String> params = new HashMap<>();
        HttpRequestUtils.getInstance().requestGet(params, url, new com.zhy.http.okhttp.callback.Callback() {
            @Override
            public Object parseNetworkResponse(Response response, int id) throws Exception {
                String fileName = "";
                Headers headers = response.headers();
                String content_disposition = headers.get("content-disposition");
                if (content_disposition.contains("fileName")) {
                    String str[] = content_disposition.split(";");
                    if (str.length >= 2) {
                        fileName = java.net.URLDecoder.decode(str[1], "UTF-8");
                        int index = fileName.indexOf("=");
                        if (index != -1) {
                            fileName = fileName.substring(index + 1);
                        }
                    }
                }


                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                File file = new File(pathFile, fileName);
                try {

                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        //下载中更新进度条
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                listener.onDownloading(progress);
                            }
                        });
                    }
                    fos.flush();
                    //下载完成

                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDownloadSuccess(file);
                        }
                    });

                } catch (Exception e) {
                    ThreadUtils.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.onDownloadFailed(e);
                        }
                    });

                } finally {

                    try {
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {

                    }
                }
                return null;
            }

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(Object response, int id) {

            }
        });

    }


    public interface OnDownloadListener {

        /**
         * 下载成功之后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载异常信息
         */

        void onDownloadFailed(Exception e);
    }
}
